import { defineStore } from 'pinia';

export const STORE_KEY_APPLICATION = 'store-application';

export type Application = {
  id?: string;
  name: string;
  type: 'client' | 'server';
  description: string;
  systemId: string;
  // 是否集成到盖亚
  isGaiYa?: boolean;
};

export const useApplicationRepository = defineStore(
  STORE_KEY_APPLICATION,
  () => {
    const applications = ref<Array<Application>>([
      {
        id: '2bca09d1-c4c3-4d05-a770-a9ea52133570',
        name: '流程引擎服务',
        type: 'server',
        description: '基于 Flowable 的流程引擎服务',
        systemId: '8f12a674-82ac-4c8d-ae90-a70a068accf9',
      },
      {
        id: '59b77efd-690f-4990-9fe5-ef21d6350bdq',
        name: '工作流平台',
        type: 'client',
        description: '独立使用工作流平台时的 Web 前端',
        systemId: '8f12a674-82ac-4c8d-ae90-a70a068accf9',
      },
    ]);

    const addApplication = (application: Application) => {
      applications.value = [application].concat(applications.value);
    };

    const getApplication = (applicationId: string) => {
      const applications_ = applications.value;
      for (let i = 0; i < applications_.length; i++) {
        const application_ = applications_[i];
        if (application_.id == applicationId) {
          return application_;
        }
      }
      return undefined;
    };

    const getApplications = (systemId: string) => {
      const applicationsOfSystem: Array<Application> = [];
      const applications_ = applications.value;
      for (let i = 0; i < applications_.length; i++) {
        const application_ = applications_[i];
        if (application_.systemId == systemId) {
          applicationsOfSystem.push(application_);
        }
      }
      return applicationsOfSystem;
    };

    return { getApplications, addApplication, getApplication };
  },
  {
    persist: {
      key: STORE_KEY_APPLICATION,
      storage: localStorage,
    },
  },
);
